package com.unlcn.ils.wms.backend.service.outbound.impl;

import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.exception.BusinessException;
import com.unlcn.ils.wms.backend.bo.outboundBO.WmsDepartureBO;
import com.unlcn.ils.wms.backend.enums.WhCodeEnum;
import com.unlcn.ils.wms.backend.enums.WmsDepartureOpenStatusEnum;
import com.unlcn.ils.wms.backend.enums.WmsDepartureTypeEnum;
import com.unlcn.ils.wms.backend.enums.WmsGateControllerTypeEnum;
import com.unlcn.ils.wms.backend.service.outbound.WmsDepartureRegisterService;
import com.unlcn.ils.wms.backend.util.DateUtils;
import com.unlcn.ils.wms.base.mapper.outbound.WmsDepartureRegisterMapper;
import com.unlcn.ils.wms.base.model.outbound.WmsDepartureRegister;
import com.unlcn.ils.wms.base.model.outbound.WmsDepartureRegisterExample;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Auther linbao
 * @Date 2017-11-14
 * 板车出库离场登记
 */
@Service
public class WmsDepartureRegisterServiceImpl implements WmsDepartureRegisterService {

    private Logger LOGGER = LoggerFactory.getLogger(WmsDepartureRegisterServiceImpl.class);

    @Autowired
    private WmsDepartureRegisterMapper departureRegisterMapper;

    /**
     * 板车离场登记分页查询
     *
     * @param wmsDepartureBO 参数封装对象
     * @param whCode         @return 返回值
     * @throws Exception 异常
     */
    @Override
    public Map<String, Object> queryDepartureListForPage(WmsDepartureBO wmsDepartureBO, String whCode) throws Exception {
        LOGGER.info("WmsDepartureRegisterServiceImpl.queryDepartureListForPage param: {},{},{}", wmsDepartureBO, whCode);
        //校验
        if (Objects.equals(wmsDepartureBO, null)) {
            throw new BusinessException("参数为空");
        }
        if (StringUtils.isBlank(whCode))
            throw new BusinessException("仓库code不能为空!");
        if (!WhCodeEnum.UNLCN_XN_CQ.getValue().equals(whCode))
            throw new BusinessException("该仓库不支持此操作!");
        //获取请求参数
        WmsDepartureRegisterExample paramMap = getParamMap(wmsDepartureBO);
        paramMap.setLimitStart(wmsDepartureBO.getStartIndex());
        paramMap.setLimitEnd(wmsDepartureBO.getPageSize());
        paramMap.setOrderByClause(" gmt_update desc ");

        //返回结果
        Map<String, Object> resultMap = new HashMap<>();
        PageVo pageVo = new PageVo();
        pageVo.setPageNo(wmsDepartureBO.getPageNo());
        pageVo.setPageSize(wmsDepartureBO.getPageSize());
        pageVo.setTotalRecord(departureRegisterMapper.countByExample(paramMap));
        resultMap.put("page", pageVo);
        resultMap.put("dataList", departureRegisterMapper.selectByExample(paramMap));
        return resultMap;
    }

    /**
     * sql参数
     *
     * @param wmsDepartureBO 参数封装对象
     */
    private WmsDepartureRegisterExample getParamMap(WmsDepartureBO wmsDepartureBO) {
        WmsDepartureRegisterExample example = new WmsDepartureRegisterExample();
        WmsDepartureRegisterExample.Criteria criteria = example.createCriteria();
        //出入场类型
        criteria.andInOutTypeEqualTo(WmsGateControllerTypeEnum.GATE_OUT.getCode());
        //车牌
        if (StringUtils.isNotBlank(wmsDepartureBO.getDrVehiclePlate())) {
            criteria.andDrVehiclePlateLike("%" + wmsDepartureBO.getDrVehiclePlate().trim() + "%");
        }
        //开闸状态
        criteria.andDrOpenStatusEqualTo(StringUtils.isBlank(wmsDepartureBO.getDrOpenStatus()) ?
                WmsDepartureOpenStatusEnum.NOT_OPEN.getValue() : Byte.valueOf(wmsDepartureBO.getDrOpenStatus()));
        //离场类型
        if (StringUtils.isNotBlank(wmsDepartureBO.getDrDepartureType())) {
            criteria.andDrDepartureTypeEqualTo(new Byte(wmsDepartureBO.getDrDepartureType()));
        }
        //离场开始时间
        if (StringUtils.isNotBlank(wmsDepartureBO.getStartDeparturTime())) {
            criteria.andDrDepartureTimeGreaterThanOrEqualTo(DateUtils.StrToDate(wmsDepartureBO.getStartDeparturTime(), DateUtils.YYYY_MM_DD));
        }
        //离场结束时间
        if (StringUtils.isNotBlank(wmsDepartureBO.getEndDepartureTime())) {
            Date endDate = DateUtils.StrToDate(wmsDepartureBO.getEndDepartureTime(), DateUtils.YYYY_MM_DD);
            endDate.setTime(endDate.getTime() + 24 * 3600000);
            criteria.andDrDepartureTimeLessThanOrEqualTo(endDate);
        }
        return example;
    }

    /**
     * 正常离场
     *
     * @param wmsDepartureBO 参数封装
     * @throws Exception 异常
     */
    @Override
    public void updateToNormalDeparture(WmsDepartureBO wmsDepartureBO) throws Exception {
        LOGGER.info("WmsDepartureRegisterServiceImpl.updateToNormalDeparture param: {}", wmsDepartureBO);
        checkBO(wmsDepartureBO, true);
        //异常离场更新
        WmsDepartureRegister updateRegister = new WmsDepartureRegister();
        updateRegister.setDrId(wmsDepartureBO.getDrId());
        updateRegister.setDrDepartureType(WmsDepartureTypeEnum.WMS_HAND.getValue());
        if (StringUtils.isNotBlank(wmsDepartureBO.getDrDepartureReason())) {
            updateRegister.setDrDepartureReason(wmsDepartureBO.getDrDepartureReason());
        }
        updateRegister.setDrDepartureTime(new Date());//离场时间
        updateRegister.setGmtUpdate(new Date());
        departureRegisterMapper.updateByPrimaryKeySelective(updateRegister);
    }

    /**
     * 异常离场
     *
     * @param wmsDepartureBO
     * @throws Exception
     */
    @Override
    public void updateToExceptionDeparture(WmsDepartureBO wmsDepartureBO) throws Exception {
        LOGGER.info("WmsDepartureRegisterServiceImpl.updateToExceptionDeparture param: {}", wmsDepartureBO);
        checkBO(wmsDepartureBO, true);
        //异常离场更新
        WmsDepartureRegister updateRegister = new WmsDepartureRegister();
        updateRegister.setDrId(wmsDepartureBO.getDrId());
        updateRegister.setDrDepartureType(WmsDepartureTypeEnum.WMS_HAND.getValue());
        if (StringUtils.isNotBlank(wmsDepartureBO.getDrDepartureReason())) {
            updateRegister.setDrDepartureReason(wmsDepartureBO.getDrDepartureReason());
        }
        updateRegister.setDrDepartureTime(new Date());//离场时间
        updateRegister.setGmtUpdate(new Date());
        departureRegisterMapper.updateByPrimaryKeySelective(updateRegister);
    }

    /**
     * 新增
     *
     * @param wmsDepartureRegister
     * @throws Exception
     */
    @Override
    public Long addDeparture(WmsDepartureRegister wmsDepartureRegister) throws Exception {
        LOGGER.info("WmsDepartureRegisterServiceImpl.addDeparture param: {}", wmsDepartureRegister);
        if (wmsDepartureRegister == null) {
            throw new BusinessException("参数为空");
        }
        if (StringUtils.isBlank(wmsDepartureRegister.getDrVehiclePlate()) || wmsDepartureRegister.getDrOpenStatus() == null) {
            throw new BusinessException("车牌和开闸状态不能为空");
        }
        departureRegisterMapper.insertSelective(wmsDepartureRegister);
        return wmsDepartureRegister.getDrId();
    }

    /**
     * 根据id获取
     *
     * @param drId
     * @return
     * @throws Exception
     */
    @Override
    public WmsDepartureRegister getByPrimarkKey(Long drId) throws Exception {
        if (drId != null) {
            return departureRegisterMapper.selectByPrimaryKey(drId);
        }
        return null;
    }

    /**
     * 校验
     *
     * @param wmsDepartureBO
     */
    private void checkBO(WmsDepartureBO wmsDepartureBO, boolean isUpdate) throws Exception {
        if (wmsDepartureBO == null) {
            throw new BusinessException("参数为空");
        }
        //校验id是否存在
        if (isUpdate) {
            if (wmsDepartureBO.getDrId() == null) {
                throw new BusinessException("参数ID为空");
            }
            WmsDepartureRegister wmsDepartureRegister = getByPrimarkKey(wmsDepartureBO.getDrId());
            if (wmsDepartureRegister == null) {
                throw new BusinessException("找不到对应的板车离场登记记录");
            }
        }
    }
}
